#include "Listener.h"


Switchboard* getSwitchboard(){
	static Switchboard* gSwitchboard=null;
	static bool initialized=false;
	if(!initialized){gSwitchboard=new Switchboard();initialized=true;}
	return gSwitchboard;
}


bool Listener::sendMessage(const char *msg,void*	params){
	bool rtn=true;
	Switchboard* board=getSwitchboard();
	std::map<const char*,growvector<Listener*>>::iterator fnd=board->routing.find(msg);
	if(fnd==board->routing.end()){
		sendMessage("unhandledMessage",(void*)msg);
		return true;
	}
	growvector<Listener*>&	listnrs=fnd->second;
	int il=listnrs.size();
	for(int i=0;i<il;i++)
		if(!listnrs[i]->message(msg,params))return false;
	return true;
}

void	Listener::listen(Listener* rcvr,const char*	msg){
	Switchboard* sb=getSwitchboard();
	sb->routing[msg].push_back(rcvr);
	rcvr->subscribe(sb,msg);
}

bool	Listener::message(const char *msg,void*	params){
	return true;
}

Listener::Listener(){
}

Listener::~Listener(){
	unsubscribe();
}

class ListenerListener : public Listener
{
public:
	virtual bool	message(const char *msg=null,void*	params=null){
		if(msg=="unhandledMessage"){
		}else if(msg=="shutdown"){
			std::map<Listener*,Listener*>	lmap;
			Switchboard*	sb = getSwitchboard();
			std::map<const char*,growvector<Listener*>>::iterator it=sb->routing.begin();
			for(;it!=sb->routing.end();it++){
				growvector<Listener*>&	ll=it->second;
				for(unsigned int t=0;t<ll.size();t++){
					lmap[ll[t]]=ll[t];
				}
			}
			std::map<Listener*,Listener*>::iterator	 lit=lmap.begin();
			for(;lit!=lmap.end();lit++){
				lit->second->unsubscribe();
			}
		}
		return true;
	}
	ListenerListener(){
		Listener::listen(this,"unhandledMessage");//Listen for this, so that we dont go into an infinite loop in message() on unhandled messages.
		Listener::listen(this,"shutdown");//Listen for this, so that we dont go into an infinite loop in message() on unhandled messages.
	}

};


ListenerListener	gListenerListener;